<?php

namespace app\admin\controller;

use app\admin\logic\statistics\MoneyStatistics;
use app\admin\model\dealer\Dealer;
use app\common\model\zbtask\Money;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\zbtask\Zbtask;
use app\common\utils\Utils;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;

/**
 * 统计
 *
 * @icon fa fa-circle-o
 */
class Statistics extends Backend
{

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Statistics');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        $statisticsModel = $this->model;

        $start_time_today = strtotime(date('Y-m-d'));
        $end_time_today = strtotime(date('Y-m-d').'+1 day');
        //用户user 总数
        $totaluser = $statisticsModel->getTotalUser();
        //经销商 总数
        $totaldealer = $statisticsModel->getTotalDealer();
        //总订单数
        $totalorder = $statisticsModel->getTotalOrder();
        //今日订单数量
        $where_today_order['createtime'] = array('between', array($start_time_today, $end_time_today));
        $totalorder_today = $statisticsModel->getTotalOrder($where_today_order);
        //总流水
        $totalorderamount = $statisticsModel->dealerAmount();
        //任务总数
        $totalzbtask = $statisticsModel->getTotalTask();
        $where_today_task['createtime'] = array('between', array($start_time_today, $end_time_today));
        $totalzbtask_today = $statisticsModel->getTotalTask($where_today_task);
        //平台总流水

        //经销商佣金

        //企业总数
        $totalcompany = $statisticsModel->countCompany();

        //今日新增企业

        $where_today['createtime'] = array('between', array($start_time_today, $end_time_today));
        $totalcompany_today = $statisticsModel->countCompany($where_today);
        //企业众包费
        $totalcompanyAmount = $statisticsModel->companyAmount();

        $this->view->assign('totaluser', $totaluser);
        $this->view->assign('totaldealer', $totaldealer);
        $this->view->assign('totalorder', $totalorder);
        $this->view->assign('totalorder_today', $totalorder_today);
        $this->view->assign('totalorderamount', $totalorderamount);
        $this->view->assign('totaltask', $totalzbtask);
        $this->view->assign('totalzbtask_today', $totalzbtask_today);
        $this->view->assign('totalcompany', $totalcompany);
        $this->view->assign('totalcompany_today', $totalcompany_today);
        $this->view->assign('totalcompanyAmount', $totalcompanyAmount);

        //订单数量走势图
        $ecdata = $this->gettaskdata();
        $this->view->assign('moneyStatics', $ecdata['moneyStatics']);
        $this->view->assign('taskStatics', $ecdata['taskStatics']);
        return $this->view->fetch();
    }

    /**
     * 企业众包费流水
     * @param null $ids
     * @return string|\think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function taskmoneycompany($ids = null){
        $statisticsModel = $this->model;

        $where_company_task = array();
        $where_total_task['company_id'] = $ids;

        //企业合众包费
        $task_id_array = model('common/zbtask/Zbtask')->where($where_total_task)->value('id', true);    //任务
        $where_company_task['task_id'] = array('in', $task_id_array);
        $companyTaskAmount = $statisticsModel->companyAmount($where_company_task);  //合众包总额

        //企业应纳税
        $tax_money = $statisticsModel->companyTaxAmount($where_company_task);
        //企业已纳税
        $already_money = $statisticsModel->companyAlreadyTaxAmount($where_company_task);

        //任务总数
        $totalTask = $statisticsModel->getTotalTask($where_total_task);

        /* $start_time_today = strtotime(date('Y-m-d'));
         $end_time_today = strtotime(date('Y-m-d').'+1 day');*/

        $this->view->assign('companyTaskAmount',  $companyTaskAmount);
        $this->view->assign('tax_money', $tax_money);
        $this->view->assign('already_money', $already_money);
        $this->view->assign('totalTask', $totalTask);

        //折线图 数据
        $ecdata = $this->gettaskdata($where_total_task);

        $this->view->assign('moneyStatics', $ecdata['moneyStatics']);
        $this->view->assign('taskStatics', $ecdata['taskStatics']);
        //流水列表数据
        if ($this->request->isAjax())
        {
            $taskMoney = new Money();
            $total = $taskMoney->alias('zbtask_money')
                ->join('zbtask zbtask', 'zbtask.id = zbtask_money.task_id')
                ->join('user user', 'zbtask_money.user_id = user.id' )
                ->where(array('zbtask.company_id'=>$ids))
                ->count();
            $zbtask_money = array();
            if($total > 0){
                $fields = array('zbtask_money.id', 'zbtask_money.money', 'zbtask_money.ca_money', 'zbtask_money.get_money', 'zbtask_money.createtime', 'zbtask.name', 'user.nickname');
                $zbtask_money = $taskMoney->alias('zbtask_money')
                    ->field($fields)
                    ->join('zbtask zbtask', 'zbtask.id = zbtask_money.task_id')
                    ->join('user user', 'zbtask_money.user_id = user.id' )
                    ->where(array('zbtask.company_id'=>$ids))
                    ->select();
            }

            //print_r($zbtask_money);
        $result = array("total" => $total, "rows" => $zbtask_money);

        return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 企业数据统计
     * @return string|\think\response\Json
     * @throws Exception
     */
    public function index_company()
    {
        //当前是否为关联查询
        $this->relationSearch = false;

        $statisticsModel = model('Statistics');

        $where_total_task = [];
        $type_id = input('type_id', 0);

        if(TYPE == 1){
            $type_id = TYPE_ID;
        }

        if($type_id){
            $where_total_task['company_id'] = $type_id;
        }

        $time_type = $this->request->request('time_type');
        $timestamp = time();
        $date_type = 'days';
        $style = 'Y-m-d';
        $length = 12;
        switch($time_type){
            case 0 :
                $start_time_today = mktime(0,0,1,1,1, date('Y'));
                $end_time_today = strtotime(date('Y-12-31 23:59:59'));
                $where_total_task['createtime'] = array('between', array($start_time_today, $end_time_today));
                $date_type = 'months';
                $style="Y-m";
                $length = 12;
                break;
            case 1 : $start_time_today = strtotime(date('Y-m-d'));
                $end_time_today = strtotime(date('Y-m-d').'+1 day');
                $where_total_task['createtime'] = array('between', array($start_time_today, $end_time_today));
                $date_type = 'hours';
                $style = 'H:00:00';
                $length = 24;
                break;
            case 2 : $start_time_weekly = strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp)));
                $end_time_weekly = strtotime(date('Y-m-d', strtotime("next week Monday", $timestamp)))  - 1;
                $where_total_task['createtime'] = array('between', array($start_time_weekly, $end_time_weekly));
                $length = 7;
                break;
            case 3 : $start_time_month = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $end_time_month = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                $where_total_task['createtime'] = array('between', array($start_time_month, $end_time_month));
                $length = date('t');
                $style="m-d";
                break;
            case 4 : $season = ceil((date('n'))/3);//当月是第几季度
                $start_time_jidu = mktime(0, 0, 0,$season*3-3+1,1,date('Y'));
                $end_time_jidu = mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'));
                $where_total_task['createtime'] = array('between', array($start_time_jidu, $end_time_jidu));
                $date_type = 'months';
                $length = 3;
                $style="Y-m";
                break;
            case 5 : $start_time_year = mktime(0,0,0,1,1,date('Y', $timestamp));
                $end_time_year = mktime(23,59,59,12,31,date('Y', $timestamp));
                $where_total_task['createtime'] = array('between', array($start_time_year, $end_time_year));
                $date_type = 'months';
                $style = "Y-m";
                break;
            case 6 : $create_time = $this->request->request('time_data');
                $time_array = explode(' - ', $create_time);
                $start_time = strtotime($time_array[0]);
                $end_time = strtotime($time_array[1]);
                $where_total_task['createtime'] = array('between', array($start_time, $end_time));
                $data = Utils::getLengthAndFormat(($end_time - $start_time));
                $date_type = $data['date_type'];
                $length = $data['length'];
                $style = $data['style'];
                break;
            default : ;break;
        }
        //企业合众包费
        $companyTaskAmount = $statisticsModel->companyAmount($where_total_task);  //合众包总额
        //企业应纳税
        $tax_money = $statisticsModel->companyTaxAmount($where_total_task);
        //企业已纳税
        $already_money = $statisticsModel->companyAlreadyTaxAmount($where_total_task);

        //任务总数
        $totalTask = $statisticsModel->getTotalTask($where_total_task);

        //折线图 数据
        $ecdata = $this->gettaskdata($where_total_task, $date_type, $style, $length);

        if ($this->request->isAjax()){

            $result = array(
                "code" => 1,
                "msg" => "数据",
                "data" => array(
                    "companyTaskAmount" => $companyTaskAmount,
                    "tax_money" => $tax_money,
                    "already_money" => $already_money,
                    "totalTask" => $totalTask,
                    "column" => array_keys($ecdata['moneyStatics']),
                    "moneydata" => array_values($ecdata['moneyStatics']),
                    "taskdata" => array_values($ecdata['taskStatics']),
                )
            );

            return json($result);
        }

        $this->view->assign('companyTaskAmount',  $companyTaskAmount);
        $this->view->assign('tax_money', $tax_money);
        $this->view->assign('already_money', $already_money);
        $this->view->assign('totalTask', $totalTask);
        $this->view->assign('moneyStatics', $ecdata['moneyStatics']);
        $this->view->assign('taskStatics', $ecdata['taskStatics']);
        $this->view->assign('type_id', $type_id);
        return $this->view->fetch();
    }

    /**
     * 经销商统计
     * @return string|\think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index_dealer(){
        //当前是否为关联查询
        $this->relationSearch = false;
        $type = TYPE;
        $dealer_id = 0;
        $where_dealer_amount = [];
        if($type == 2){
            $dealer_id = TYPE_ID;
            $where_dealer_amount['dealer_com.dealer_id'] = $dealer_id;
        }

        $time_type = $this->request->request('time_type');
        $timestamp = time();
        $where_dealer = [];
        $where_dealer_with = [];
        $where_dealer_com = [];
        switch($time_type){
            case 0 :
                $start_time_today = mktime(0,0,1,1,1, date('Y'));
                $end_time_today = strtotime(date('Y-12-31 23:59:59'));
                $where_dealer_com['dealer_com.createtime'] = $where_dealer['createtime'] = array('between', array($start_time_today, $end_time_today));
                $where_dealer_with['money_log.createtime'] = array('between', array($start_time_today, $end_time_today));
                $where_dealer_amount['money.createtime'] = array('between', array($start_time_today, $end_time_today));
                break;
            case 1 : $start_time_today = strtotime(date('Y-m-d'));
                $end_time_today = strtotime(date('Y-m-d').'+1 day');
                $where_dealer_com['dealer_com.createtime'] = $where_dealer['createtime'] = array('between', array($start_time_today, $end_time_today));
                $where_dealer_with['money_log.createtime'] = array('between', array($start_time_today, $end_time_today));
                $where_dealer_amount['money.createtime'] = array('between', array($start_time_today, $end_time_today));
                break;
            case 2 : $start_time_weekly = strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp)));
                $end_time_weekly = strtotime(date('Y-m-d', strtotime("next week Monday", $timestamp)))  - 1;
                $where_dealer_com['dealer_com.createtime'] = $where_dealer['createtime'] = array('between', array($start_time_weekly, $end_time_weekly));
                $where_dealer_amount['money.createtime'] = array('between', array($start_time_weekly, $end_time_weekly));
                $where_dealer_with['money_log.createtime'] = array('between', array($start_time_weekly, $end_time_weekly));
                break;
            case 3 : $start_time_month = mktime(0, 0, 0, date('m'), 1, date('Y'));
                $end_time_month = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                $where_dealer_com['dealer_com.createtime'] = $where_dealer['createtime'] = array('between', array($start_time_month, $end_time_month));
                $where_dealer_amount['money.createtime'] = array('between', array($start_time_month, $end_time_month));
                $where_dealer_with['money_log.createtime'] = array('between', array($start_time_month, $end_time_month));
                break;
            case 4 : $season = ceil((date('n'))/3);//当月是第几季度
                $start_time_jidu = mktime(0, 0, 0,$season*3-3+1,1,date('Y'));
                $end_time_jidu = mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y'));
                $where_dealer_com['dealer_com.createtime'] = $where_dealer['createtime'] = array('between', array($start_time_jidu, $end_time_jidu));
                $where_dealer_amount['money.createtime'] = array('between', array($start_time_jidu, $end_time_jidu));
                $where_dealer_with['money_log.createtime'] =  array('between', array($start_time_jidu, $end_time_jidu));
                break;
            case 5 : $start_time_year = mktime(0,0,0,1,1,date('Y', $timestamp));
                $end_time_year = mktime(23,59,59,12,31,date('Y', $timestamp));
                $where_dealer_com['dealer_com.createtime'] = $where_dealer['createtime'] = array('between', array($start_time_year, $end_time_year));
                $where_dealer_amount['money.createtime'] = array('between', array($start_time_year, $end_time_year));
                $where_dealer_with['money_log.createtime'] = array('between', array($start_time_year, $end_time_year));
                break;
            case 6 : $create_time = $this->request->request('time_data');$time_array = explode(' - ', $create_time);
                $where_dealer_com['dealer_com.createtime'] = $where_dealer['createtime'] = array('between', array(strtotime($time_array[0]), strtotime($time_array[1])));
                $where_dealer_amount['money.createtime'] = array('between', array(strtotime($time_array[0]), strtotime($time_array[1])));
                $where_dealer_with['money_log.createtime'] = array('between', array(strtotime($time_array[0]), strtotime($time_array[1])));
                break;
            default :

                ;break;
        }

        //经销商提现金额
        $usermoney = model('admin/dealer/Dealer')->getDealerUsermoney($dealer_id);    //现余额
        $dealer_amount = MoneyStatistics::instance()->setWhere($where_dealer_amount)->getDealerMoney();    //佣金总额
        //累计提现
        $withdraw_amount = model('admin/dealer/MoneyLog')->getWithdrawAmount($dealer_id, $where_dealer_with);

        //众包费总流水
        $dealer_task_money = $this->model->dealerAmount($dealer_id, $where_dealer);

        //企业佣金比例列表
        $dealer_company_list = $this->model->getDealerCompanyList($dealer_id, $where_dealer_com);
        //未提现总额
        $dealer_usermoney = model('admin/dealer/Dealer')->getDealerUsermoney();

        if($type == 2) {
            //企业数量
            $company_num = $this->model->dealerCompanyCount($dealer_id);
            $company_num_title = '企业数量';
        }else if($type == 0){
            //经销商数量
            $company_num = (new Dealer())->where($where_dealer)->count();
            $company_num_title = '经销商数量';
        }

        if ($this->request->isAjax()){
            $result = array(
                "code" => 1,
                "msg" => "数据",
                "data" => array(
                    "withdraw_amount" => $withdraw_amount,
                    "dealer_task_amount" => $dealer_task_money,
                    "company_num" => $company_num,
                    "dealer_amount" =>$dealer_amount,
                    "dealer_usermoney" =>$dealer_usermoney,
                    "dealer_company_list" => $dealer_company_list,
                )
            );

            return json($result);
        }

        $this->view->assign('withdraw_amount', $withdraw_amount);
        $this->view->assign('dealer_task_amount', $dealer_task_money);
        $this->view->assign('company_num', $company_num);
        $this->view->assign('dealer_company_list', $dealer_company_list);
        $this->view->assign('company_num_title', $company_num_title);
        $this->view->assign('dealer_amount', $dealer_amount);
        $this->view->assign( 'dealer_usermoney',  $dealer_usermoney);
        $this->view->assign('type', TYPE);

        return $this->view->fetch();
    }

    /**
     * 图表统计数据
     * @param array $where_data 筛选条件
     * @param string $date_type 时间间隔区间   hours   days  months
     * @param string $show_style  时间展示样式
     * @param int $date_lenght  时间间隔长度
     * @return array
     * @throws Exception
     */
    private function gettaskdata($where = [],  $date_type = 'days', $show_style = 'Y-m-d', $date_lenght = 12){
        $end_time = time();
        if(isset($where['createtime'])){
            $end_time =  $where['createtime'][1][1]+1; //时间区间 结束时间  筛选时 设置 当天23：59：59， 形成图表时，取日期有误
        }
        //echarts 流水，任务统计
        $moneyStatics = [];
        $taskStatics = [];

        for($i = 1; $i <= $date_lenght; $i++) {
            if ($i == 1) {
                $start = strtotime ((-$i). ' '. $date_type, $end_time);
                $end = $end_time;
            } else {
                $start = strtotime ((-$i). ' '. $date_type, $end_time);
                $end = strtotime ((-$i+1). ' '. $date_type, $end_time);
            }
            $startTime = $start;
            $endTime = $end;

            $where['status'] = 1;
            $where['type'] = 1;
            $where['createtime'] = array('between', [$startTime, $endTime]);
            //print_r($where['createtime']);
            $allMoney = Money::where($where)->sum('money');
            $allTasks = Zbtask::where($where)->count();
            $startFormat = Utils::time_format($startTime,  $show_style);

            $moneyStatics[$startFormat] = $allMoney;
            $taskStatics[$startFormat] = $allTasks;
        }
        return array('moneyStatics'=>array_reverse($moneyStatics), 'taskStatics'=>array_reverse($taskStatics));
    }
}
